package jp.co.sharp.android.parents.kidsguard.activity.setting.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.AlarmActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PeriodSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PeriodSettingWeekActivity;
import jp.co.sharp.android.parents.kidsguard.common.DateTimePickerDlg;
import jp.co.sharp.android.parents.kidsguard.dto.NotifyListDto;

public class PeriodSettingItemAdaptor extends ArrayAdapter<NotifyListDto> {
    private int resourceId;
    private OnClickItemListenter onClickItemListenter;
    private Context mContext;

    @Override
    public boolean areAllItemsEnabled() {
        return super.areAllItemsEnabled();
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource) {
        super(context, resource);
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource, int textViewResourceId) {
        super(context, resource, textViewResourceId);
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource, @NonNull NotifyListDto[] objects) {
        super(context, resource, objects);
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource, int textViewResourceId, @NonNull NotifyListDto[] objects) {
        super(context, resource, textViewResourceId, objects);
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource, @NonNull List<NotifyListDto> objects, OnClickItemListenter onClickItemListenter) {
        super(context, resource, objects);
        this.resourceId = resource;
        this.onClickItemListenter = onClickItemListenter;
        this.mContext = context;
    }

    public PeriodSettingItemAdaptor(@NonNull Context context, int resource, int textViewResourceId, @NonNull List<NotifyListDto> objects) {
        super(context, resource, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View converView, ViewGroup parent) {
        NotifyListDto notifyListDto = getItem(position);

        View view;
        ViewHolder viewHolder;

        if (null == converView) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);

            viewHolder = new PeriodSettingItemAdaptor.ViewHolder();
            viewHolder.beginTime = view.findViewById(R.id.beginTime);
            viewHolder.endTime = view.findViewById(R.id.endTime);
            viewHolder.week = view.findViewById(R.id.week);
            viewHolder.state = view.findViewById(R.id.state);
            viewHolder.name = view.findViewById(R.id.name);
            viewHolder.beginTimeLayout = view.findViewById(R.id.beginTimeLayout);
            viewHolder.endTimeLayout = view.findViewById(R.id.endTimeLayout);
            viewHolder.noLayout = view.findViewById(R.id.noLayout);
            viewHolder.del = view.findViewById(R.id.del);

            view.setTag(viewHolder);
        } else {
            view = converView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.beginTime.setText(notifyListDto.getBeginTime());
        viewHolder.endTime.setText(notifyListDto.getEndTime());

        viewHolder.week.setText("1回のみ");

        viewHolder.week.setText(formatWeek(notifyListDto.getWeekday(), notifyListDto));


        viewHolder.name.setText("設定" + (position + 1));


        viewHolder.beginTimeLayout.setOnClickListener(new StartTimeClick());
        viewHolder.endTimeLayout.setOnClickListener(new EndTimeClick());
        viewHolder.noLayout.setOnClickListener(new WeekOnClick());
        viewHolder.del.setOnClickListener(new Delete());
        viewHolder.state.setOnCheckedChangeListener(new StateListener(position));
        if (notifyListDto.getState() == 0) {
            viewHolder.state.setChecked(true);
        } else {
            viewHolder.state.setChecked(false);
        }
        viewHolder.state.setTag(position);
        viewHolder.beginTimeLayout.setTag(position);
        viewHolder.endTimeLayout.setTag(position);
        viewHolder.noLayout.setTag(position);
        viewHolder.del.setTag(position);
        return view;
    }

    class ViewHolder {
        LinearLayout beginTimeLayout;
        LinearLayout endTimeLayout;
        LinearLayout noLayout;
        TextView beginTime;
        TextView endTime;
        TextView week;
        TextView name;
        Switch state;
        TextView del;
    }

    public interface OnClickItemListenter {
        void chooseItemClick(int position);
    }

    //    /*
//     * 对外公开方法让Activity实现
//     */
//    public void OnDelBluetoothListenter(OnClickItemListenter callBack) {
//        onClickItemListenter = callBack;
//    }
//
//    class ChooseItemListenter implements View.OnClickListener {
//
//        @Override
//        public void onClick(View view) {
//            onClickItemListenter.chooseItemClick((Integer)view.getTag(), view);
//        }
//    }
    class StateListener implements CompoundButton.OnCheckedChangeListener {
        int position;

        StateListener(int p) {
            position = p;
        }

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            NotifyListDto notifyListDto = getItem(position);
            if (checked) {
                notifyListDto.setState(0);
            } else {
                notifyListDto.setState(1);
            }
        }
    }


    class StartTimeClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            NotifyListDto notifyListDto = getItem((Integer) v.getTag());
            int[] timeNum = formatTimeToNum(notifyListDto.getBeginTime());

            DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(mContext, R.style.dateTimePicker, timeNum[0], timeNum[1], timeNum[2]);
            dateTimePickerDlg.show();
            dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
                @Override
                public void onDateTimeSet(int pAmPm, int pHour, int pMinute) {
                    NotifyListDto notifyListDto = getItem((Integer) v.getTag());
                    notifyListDto.setBeginTime(formatTime(pAmPm, pHour, pMinute));
//                    onClickItemListenter.chooseItemClick((Integer) v.getTag());
                    TextView textView = (TextView) v.findViewById(R.id.beginTime);
                    textView.setText(notifyListDto.getBeginTime());

                }
            });
        }
    }

    class EndTimeClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            NotifyListDto notifyListDto = getItem((Integer) v.getTag());
            int[] timeNum = formatTimeToNum(notifyListDto.getEndTime());

            DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(mContext, R.style.dateTimePicker, timeNum[0], timeNum[1], timeNum[2]);
            dateTimePickerDlg.show();
            dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
                @Override
                public void onDateTimeSet(int pAmPm, int pHour, int pMinute) {
                    NotifyListDto notifyListDto = getItem((Integer) v.getTag());
                    notifyListDto.setEndTime(formatTime(pAmPm, pHour, pMinute));
//                    onClickItemListenter.chooseItemClick((Integer) v.getTag());
                    TextView textView = (TextView) v.findViewById(R.id.endTime);
                    textView.setText(notifyListDto.getEndTime());
                }
            });
        }
    }

    class WeekOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            NotifyListDto notifyListDto = getItem((Integer) v.getTag());
            Intent intent = new Intent(mContext, PeriodSettingWeekActivity.class);
            intent.putExtra("position", (Integer) v.getTag() + "");
            if (notifyListDto.getWeekday() == 0) {
                String[] weeks = {"40", "01", "02", "04", "08", "10", "20"};
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                if (w < 0) {
                    w = 0;
                }
                int repetition = Integer.parseInt(weeks[w]);
                intent.putExtra("repetition", repetition);
            } else {
                intent.putExtra("repetition", notifyListDto.getWeekday());
            }
            int PeriodSettingRequestCode = 1;
            PeriodSettingActivity.mPageJumpFlag = true;
            ((Activity) mContext).startActivityForResult(intent, PeriodSettingRequestCode);
        }
    }

    class Delete implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            onClickItemListenter.chooseItemClick((Integer) v.getTag());
//            this.notifyRemove((Integer) v.getTag());
        }
    }

    public String formatWeek(Integer repetition, NotifyListDto notifyListDto) {
        String repeatText = "1回のみ";
        if (repetition != 0) {
            List<String> repetitionList = AlarmActivity.repetitionToStirng(Integer.toHexString(repetition));
            StringBuffer contentText = new StringBuffer();
            for (String week : repetitionList) {
                contentText.append(week);
                contentText.append(" ");
            }
            repeatText = contentText.toString();
        }
        else if(notifyListDto.getNo() != -1 && repetition == 0){
            String[] weeks = {"40", "01", "02", "04", "08", "10", "20"};
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0) {
                w = 0;
            }
            List<String> strings = AlarmActivity.repetitionToStirng(weeks[w]);
            repeatText = strings.get(0).toString();
        }
        return repeatText;
    }

    public int[] formatTimeToNum(String time) {
        String str = time.substring(2);
        String[] split = str.split(":");

        Integer pAmPm = 0;
        Integer pHour = Integer.parseInt(split[0]);
        if (time.substring(0, 2).equals("午後")) {
            pAmPm = 1;
        }
        ;
        int[] timeNum = new int[3];
        timeNum[0] = pAmPm;
        timeNum[1] = pHour;
        timeNum[2] = Integer.parseInt(split[1]);
        return timeNum;
    }

    public String formatTime(int pAmPm, int pHour, int pMinute) {
        String pm = "";
        String hour = pHour + "";
        String min = pMinute + "";
        if (pAmPm == 0) {
            pm = "午前";
        } else {
            pm = "午後";
        }
        if (pHour < 10) {
            hour = "0" + pHour;
        }
        if (pMinute < 10) {
            min = "0" + pMinute;
        }
        return pm + hour + ":" + min;
    }
}
